#include "tcp.h"

#define INFOFILE ".info"
int main(int argc, char*argv[]){

	int fd, file_fd;
	int ret;
	FILE *fp;
	char buf[BUFSIZ];
	char *filename = argv[1];

	if(argc < 2){
		printf("%s <filename>\n", argv[0]);
		exit(0);
	}

	/*通过配置文件获取IP地址和端口号*/
	if ( (fp = fopen(INFOFILE, "r") ) == NULL)
		ErrExit("fopen");
	fgets(buf, 20, fp);
	buf[strlen(buf) - 1] = '\0';
	argv[1] = buf;
	fgets(&buf[20], 20, fp);
	buf[strlen(&buf[20]) - 1 + 20] = '\0';
	argv[2] = &buf[20];

	/*测试上面程序
	printf("%s\n%s\n", argv[1], argv[2]);
	getchar();
	*/

	/*创建套接字*/
	fd = SocketInit(argv, false);

	/*打开文件*/
	if( (file_fd = open(filename, O_RDONLY)) < 0)
		ErrExit("open");
	
	/*发送文件名字*/
	SocketDataHandle(fd, filename, strlen(filename), (DataHand_t)send);
	SocketDataHandle(fd, buf, 1, recv);

	/*发送文件内容*/
	if(buf[0] == OK){
		while(1){
			do{
				ret = read(file_fd, buf, BUFSIZ) < 0;
			}while(ret < 0 && errno == EINTR);		
			if(ret < 0)
				ErrExit("read");
			if(!ret)
				break;
			ret = SocketDataHandle(fd, buf, ret, (DataHand_t)send);
			if(!ret)
				break;
		}
	}
	/*
	while(1){
		ret = SocketDataHandle(fd, buf, strlen(buf), (DataHand_t)send);
		if(!ret)
			break;
		printf("send data:%s", buf);
		fflush(stdout);
		getchar();
	}
	*/
	close(file_fd);
	close(fd);	
	return 0;
}
